package com.wsm.springBoot.controller;

import com.wsm.springBoot.Exception.MyException;
import com.wsm.springBoot.annotation.LogAnnotation;
import com.wsm.springBoot.utils.RandomValidateCodeUtil;
import com.wsm.springBoot.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.Map;

/**
 * @name: LoginApi
 * @Author: wangshimin
 * @Date: 2019/11/13  14:27
 * @Description:
 */
@Api(tags = {"Shiro登录管理"})
@RestController
public class LoginController {

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            //输出验证码图片方法
            Map<String, Object> randcode = randomValidateCode.getRandcode();
            HttpSession session = request.getSession();
            //将生成的随机字符串保存到session中
            session.removeAttribute("sessionKey");
            session.setAttribute("sessionKey", randcode.get("randomString"));
            BufferedImage image = (BufferedImage) randcode.get("image");
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            System.out.println("获取验证码失败>>>> " + e.toString());
        }
    }

    @LogAnnotation
    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            token.setRememberMe(true);
        } catch (UnknownAccountException e) {
            throw new MyException(0, "账户名不存在");
        } catch (IncorrectCredentialsException e) {
            throw new MyException(0, "密码不正确");
        } catch (LockedAccountException e) {
            throw new MyException(0, "账户被锁定");
        }
        return Result.success();
    }


    @LogAnnotation
    @ApiOperation(value = "没有权限跳转地址")
    @RequestMapping(value = "/unauthc", method = RequestMethod.GET)
    public void unAuthc() {
        throw new MyException(0, "没有权限");
    }


    @LogAnnotation
    @ApiOperation(value = "未登录跳转地址")
    @RequestMapping(value = "/getLogin", method = RequestMethod.GET)
    public void getLogin() {
        throw new MyException(0, "请先登录");
    }

    @LogAnnotation
    @ApiOperation(value = "退出")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.success();
    }
}
